#include <ArduinoJson.hpp>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "HX711.h"

#define LCD_STK 10
#define LCD_DT 6
// 1. Replace with your network credentials

float Weight = 0;
float Height;
int age;
String gender;
const char* ssid = "rayvin";
const char* password = "ljw192874";

// Replace with your OpenAI API key
//const char* apiKey = "KWAlR7TtNpffHYNOTG2hm83b";
//const char* secret_Key = "emxGl4EJ2TjKkqFPopdhCdgGdMhQ8pNt";
//const char* access_token = "24.83047209f903c1a479da3e05a8e646bc.2592000.1737369618.282335-116620460";
// Send request to OpenAI API
String inputText = "你好";
// 2. Replace with your access_token
String apiUrl = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-4.0-turbo-128k?access_token=24.ab59340678906750bfafb48d1033616e.2592000.1736430180.282335-116620460";
String answer;
void printweight()
{
  Weight = Get_Weight();    //计算放在传感器上的重物重量
  Serial.print("您的体重是：");
    Serial.print(float(Weight/1000),3);    //串口显示重量
    Serial.print(" kg\n");    //显示单位
  Serial.print("能给我提供更多你的信息吗？比如身高、年龄、性别\n");
}
String getGPTAnswer(String inputText) {
  HTTPClient http;
  http.setTimeout(30000);
  http.begin(apiUrl);
  http.addHeader("Content-Type", "application/json");
  // http.addHeader("access_token", String(access_token));
  String payload = "{\"messages\":[{\"role\": \"user\",\"content\": \"" + inputText + "\"}],\"disable_search\": false,\"enable_citation\": false}";
  int httpResponseCode = http.POST(payload);
  if (httpResponseCode == 200) {
    String response = http.getString();
    http.end();
    // Parse JSON response
    DynamicJsonDocument jsonDoc(4096);
    deserializeJson(jsonDoc, response);
    String outputText = jsonDoc["result"];
    return outputText;
    // Serial.println(outputText);
  } else {
    http.end();
    Serial.printf("Error %i \n", httpResponseCode);
    return "<error>";
  }
}

void setup() {
  // Initialize Serial
  Serial.begin(9600);

  // Connect to Wi-Fi network
  Init_Hx711();                //初始化HX711模块连接的IO设置
    Serial.begin(9600);
    Serial.print("Welcome to use!\n");
    delay(3000);
    Get_Maopi();        //获取毛皮
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
  answer = getGPTAnswer(inputText);
  Serial.println("Answer: " + answer);
  Serial.println("Enter a prompt:");

}

void loop() {
  // do nothing
  if (Serial.available()) {
    inputText = Serial.readStringUntil('\n');
    Serial.println("question:"+inputText);
    // inputText.trim();
      
    if(inputText=="weight")
      {
        printweight();
        Serial.print("你的身高(cm):");
        Serial.read();
        while (Serial.available() == 0) 
        {
        }
        Height = Serial.parseFloat();
        Serial.println(Height);
        Serial.print("你的年龄(岁):");
        Serial.read();
        while (Serial.available() == 0) 
        {
        }
        
        age = Serial.parseInt();
        Serial.println(age);
        Serial.print("你的性别(男/女):");
        Serial.read();
        while (Serial.available() == 0) 
        {
        }
        gender = Serial.readStringUntil('\n');
        Serial.println(gender);
        Serial.println("尚食子正在为你规划饮食方案中，请稍后...\n");
        char formattedInputText[300]; // 创建一个足够大的字符数组来存储格式化后的字符串
        sprintf(formattedInputText, "我的体重是%f kg，我的身高是%f cm，我的年龄是%d 岁，我的性别是%s，能给我一份简单的适合我的食谱（一日三餐）吗，以及它的具体营养成分含量和做法", Weight/1000,Height,age,gender); //
        inputText=formattedInputText;
      }
    answer = getGPTAnswer(inputText);
    Serial.println("Answer: " + answer);
    Serial.println("Enter a prompt:");
  }
  // delay(2);
}
